package com.example.controller;


import com.example.pojo.Article;
import com.example.pojo.PageBean;
import com.example.pojo.Result;
import com.example.service.ArticleService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/article")
@RequiredArgsConstructor
public class ArticleController {

    private final ArticleService articleService;


    /**
     * 新增文章
     *
     * @param article 文章
     */
    @PostMapping
    public Result<String> add(@RequestBody @Validated(Article.Add.class) @Valid Article article) {

        articleService.add(article);
        return Result.success();
    }

    /**
     * 文章列表（分页查询）
     *
     * @param pageNum    当前页码
     * @param pageSize   每条页数
     * @param categoryId 文章分类ID 非必须
     * @param state      发布状态    已发布|草稿     非必须
     * @return 文章列表
     */
    @GetMapping
    public Result<PageBean<Article>> list(final Integer pageNum, final Integer pageSize,
                                          @RequestParam(required = false) final Integer categoryId,
                                          @RequestParam(required = false) final String state) {

        PageBean<Article> pageBean = articleService.list(pageNum, pageSize, categoryId, state);

        return Result.success(pageBean);
    }

    /**
     * 获取文章详情
     *
     * @param id 主键id
     */
    @GetMapping("/detail")
    public Result<Article> detail(@NotNull final Integer id) {
        Article article = articleService.findById(id);

        return Result.success(article);
    }

    /**
     * 更新文章
     *
     * @param article 新的文章内容
     */
    @PutMapping
    public Result<String> update(@RequestBody @Validated(Article.Update.class) Article article) {
        articleService.update(article);

        return Result.success();
    }


    /**
     * 删除文章
     *
     * @param id 文章主键ID
     */
    @DeleteMapping
    public Result<String> delete(final Integer id) {
        articleService.delete(id);
        return Result.success();
    }

}
